package ch.sv7.tool.dbmanager.db.fix;

import ch.sv7.tool.dbmanager.db.ColumnSchema;
import ch.sv7.tool.dbmanager.db.SchemaElement;
import ch.sv7.tool.dbmanager.db.dialect.DialectException;

/**
 * TODO: Document me!
 *
 * @author svt
 *
 */
public class CopyColumnFix extends AbstractSchemaFix implements SchemaFix {

	private ColumnSchema fromColumn;
	private ColumnSchema toColumn;
	private boolean autoIncrement;

	/**
	 * @param fromColumn
	 * @param toColumn
	 */
	public CopyColumnFix(ColumnSchema fromColumn, ColumnSchema toColumn) {
		super();
		this.fromColumn = fromColumn;
		this.toColumn = toColumn;
	}

	public SchemaElement getActionTarget() {
		return toColumn;
	}

	/**
	 * @return the autoIncrement
	 */
	public boolean isAutoIncrement() {
		return autoIncrement;
	}


	/**
	 * @param autoIncrement the autoIncrement to set
	 */
	public void setAutoIncrement(boolean autoIncrement) {
		this.autoIncrement = autoIncrement;
	}


	public String getSQLFix() throws DialectException {
		StringBuffer ddl = new StringBuffer();
		boolean sameTypes = fromColumn.getType().getTypeName().equals(toColumn.getType().getTypeName());
		if (sameTypes){
			ddl.append("\n-- Data copy\n");
		} else {
			ddl.append("\n-- Data copy with explicit conversion convert()\n");
		}
		if (autoIncrement){
			ddl.append(getDialect().getDisableAutoIncrementDDL(toColumn));
		}
		ddl.append("update " + toColumn.getTable().getName());
		ddl.append(" set " + toColumn.getName());
		if (sameTypes){
			if (toColumn.getType().hasDefaultValue()){
				ddl.append(" = coalesce(" + fromColumn.getName()+ "," + toColumn.getType().getDefaultValue() + ")" +getDialect().getStatementDelimiter() + "\n");
			} else {
				ddl.append(" = " + fromColumn.getName()+ getDialect().getStatementDelimiter() + "\n");
			}
		} else {
			if (toColumn.getType().hasDefaultValue()){
				ddl.append(" = coalesce(convert(" + toColumn.getType().getTypeName() + "," + fromColumn.getName() + ")," + toColumn.getType().getDefaultValue() + ")" + getDialect().getStatementDelimiter() + "\n");
			} else {
				ddl.append(" = convert(" + toColumn.getType().getTypeName() + "," + fromColumn.getName() + ")" + getDialect().getStatementDelimiter() + "\n");
			}
		}
		if (autoIncrement){
			ddl.append(getDialect().getEnableAutoIncrementDDL(toColumn));
		}
		return ddl.toString();	
	}

	public int getPriority() {
		return SchemaFix.PRIORITY_COLUMN_COPY;
	}

	public String getDescription() {
		return "Copying data to table " + toColumn.getTable() + " column " + toColumn.getName();
	}

	public int getAction() {
		return ACTION_COPY_DATA;
	}

}
